package com.ulook.lookplanet.ui.home.my;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ulook.lookplanet.base.BaseViewModel2;
import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.ui.square.VArticlePreInfo;
import com.ulook.lookplanet.util.ThrowException;
import com.ulook.lookplanet.util.json.JacksonUtil;
import com.ulook.lookplanet.util.net.AsynRequestUtil;
import com.ulook.lookplanet.util.net.OkHttpException;
import com.ulook.lookplanet.util.net.RequestParams;
import com.ulook.lookplanet.util.net.ResponseCallback;

import java.util.List;

/**
 * 描述：
 *
 * @author L1998
 * @data 2021/6/2
 */
public class MyArtViewModel extends BaseViewModel2 {

    private MutableLiveData<List<VArticlePreInfo>> artInfos = new MutableLiveData<>();
    private int currUserId;

    public LiveData<List<VArticlePreInfo>> getArtInfos(){
        return artInfos;
    }

    public int getCurrUserId() {
        return currUserId;
    }

    public void setCurrUserId(int currUserId) {
        this.currUserId = currUserId;
    }

    /**
     * 加载数据
     */
    public void getArticleData(int itemNum){

        ResponseCallback callback = new ResponseCallback() {
            @Override
            public void onSuccess(Object res) {
                try {
                    List<VArticlePreInfo> articlePreInfos = JacksonUtil.json2list((String)res, VArticlePreInfo.class);
                    if(articlePreInfos.size() == 0){
                        setToastText("获取动态失败");
                        return;
                    }
                    artInfos.setValue(articlePreInfos);
                } catch (Exception e) {
                    setToastText("获取动态解析数据失败");
                    ThrowException.print(e);
                }
            }
            @Override
            public void onFailure(OkHttpException failuer) {
                setToastText(failuer.getEmsg());
                ThrowException.print(failuer, failuer.getEmsg());
            }
        };
        RequestParams params = new RequestParams();
        params.put("currUserId", currUserId);
        params.put("itemNum", itemNum);

        AsynRequestUtil.post(AppServer.ROOT_PATH + "/topic/getArticleByUserId", params, null, callback);
    }

    /**
     * 删除动态
     */
    public void deleteArticle(String uid, int pos){
        List<VArticlePreInfo> list = artInfos.getValue();
        ResponseCallback callback = new ResponseCallback() {
            @Override
            public void onSuccess(Object res) {
                setToastText("删除成功");
                list.remove(pos);
            }
            @Override
            public void onFailure(OkHttpException failuer) {
                setToastText("删除失败");
            }
        };
        RequestParams params = new RequestParams();
        params.put("uid", uid);
        AsynRequestUtil.post(AppServer.ROOT_PATH + "/topic/deleteArticleByUid", params, null, callback);
    }
}
